//
//  ShareHandler.swift
//  
//
//  Created by 孙长坦 on 2022/12/3.
//

import Foundation
import WebKit
import LibBase


class ShareHandler: WebViewHandlerProtocol {
    static var id: String = "share"
    
    
    func handler(_ handler: WebViewHandlerProtocol,
                 webView: WKWebViewEx?,
                 frameInfo: WKFrameInfo,
                 params: [String: Any]?) {
        guard let webView = webView else {
            return
        }
        
        guard let params = params,
              let uuid = params["uuid"] as? String else {
            return
        }
        
        guard let shareObject = params["shareObject"] as? [String: Any] else {
            runFailCallback(webView: webView,
                            uuid: uuid,
                            code: 1,
                            message: "share:fail, no share object",
                            handlerParams: params)
            return
        }
        
        let shareCompletion: ShareProtocol.Completion = { [weak self] success in
            if success {
                self?.runSuccessCallback(webView: webView,
                                         uuid: uuid,
                                         code: 0,
                                         message: "share:ok",
                                         data: nil,
                                         handlerParams: params)
            } else {
                self?.runFailCallback(webView: webView,
                                      uuid: uuid,
                                      code: 1,
                                      message: "share:fail",
                                      handlerParams: params)
            }
        }
        
        if let shareType = params["shareType"] as? String {
            SDKManager.shared.share(type: shareType, shareObject: shareObject, completion: shareCompletion)
        } else {
            SDKManager.shared.share(shareObject: shareObject, completion: shareCompletion)
        }
    }
}
